import schedule
import subprocess
import time
import signal
import sys
import os

# 全局变量，用于存储子进程
child_process = None

def restart_program():
    """重启目标程序（非阻塞方式）"""
    global child_process
    print("正在重启程序...")

    # 如果已有子进程在运行，先终止它
    if child_process and child_process.poll() is None:
        print("终止当前运行的程序...")
        child_process.terminate()
        child_process.wait()  # 等待子进程完全退出

    try:
        # 使用Popen以非阻塞方式启动程序
        child_process = subprocess.Popen([sys.executable, 'AutoCatch.py'],env=os.environ.copy())
        print(f"程序已启动，PID: {child_process.pid}")
    except Exception as e:
        print(f"启动程序失败: {e}")


def schedule_restart():
    """设置定时重启任务"""
    schedule.every().monday.at("06:00").do(restart_program)
    print("已设置每周一06:00重启自动接龙程序")
    # schedule.every().minute.do(restart_program)
    # print("已设置每分钟重启程序")


def signal_handler(sig, frame):
    """处理Ctrl+C信号"""
    global child_process
    print("\n接收到停止信号，正在终止程序...")

    # 终止子进程
    if child_process and child_process.poll() is None:
        child_process.terminate()  # 发送SIGTERM信号
        try:
            # 等待子进程退出，超时后强制杀死
            child_process.wait(timeout=5)
            print("子进程已成功终止")
        except subprocess.TimeoutExpired:
            child_process.kill()  # 发送SIGKILL信号
            print("子进程超时未响应，已强制终止")

    print("主程序退出")
    sys.exit(0)


if __name__ == "__main__":
    # 注册信号处理函数
    signal.signal(signal.SIGINT, signal_handler)

    # 设置定时重启任务
    schedule_restart()

    # 首次启动程序
    restart_program()

    print("主程序运行中，按Ctrl+C停止...")
    try:
        while True:
            schedule.run_pending()
            time.sleep(1)
    except Exception as e:
        print(f"发生异常: {e}")
    finally:
        # 确保在任何情况下都尝试终止子进程
        if child_process and child_process.poll() is None:
            child_process.terminate()